package com.ruoyi.web.controller.publish;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.publish.constant.ReviewConstant;
import com.ruoyi.publish.domain.IdExpert;
import com.ruoyi.publish.domain.IdLaw;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.publish.domain.RvSample;
import com.ruoyi.publish.service.IRvSampleService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.IIOException;

/**
 * 审读样本Controller
 *
 * @author confusefox
 * @date 2020-11-02
 */
@Controller
@RequestMapping("/publish/sample")
public class RvSampleController extends BaseController {
    private String prefix = "publish/sample";

    // 资源文件路径
    //private final String datapath = "src/resources";
    //private final String testResourcesDataPath = "src/resources/test-data";
    //private final String testResourcesLanguagePath = "src/main/resources/tessdata";
    @Value("${ruoyi.tessPath}")
    private String testResourcesLanguagePath;


    @Autowired
    private IRvSampleService rvSampleService;

    //    @RequiresPermissions("publish:sample:view")
    @GetMapping()
    public String sample() {
        return prefix + "/sample";
    }


    @RequestMapping("/sampleSelect")
    public String sampleSelect() {
        return prefix + "/sampleSelect";
    }


    /**
     * 通用上传请求
     */
    @PostMapping("/picUpload")
    @ResponseBody
    public AjaxResult picUpload(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = Global.getUploadPath() + "/pic";
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            //String url = serverConfig.getUrl() + fileName;
//            System.out.println("picToWord");
//            logger.info("picToWord");
//            ITesseract instance = new Tesseract();
            //Constants.RESOURCE_PREFIX
            String absolutPath = Global.getProfile() + fileName.substring(Constants.RESOURCE_PREFIX.length());
            File imageFile = new File(absolutPath);
            //set language
//            String clazzpath = ResourceUtils.getURL("classpath:").getPath();
//            instance.setDatapath(testResourcesLanguagePath);
//            instance.setLanguage("chi_sim");
//            String result = instance.doOCR(imageFile);
//            logger.info(result);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
//            ajax.put("result", result);
            return ajax;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 通用上传请求
     * msg 一张。或多张全部   识别失败：无法识别
     * 多张中的部分失败失败：有图片无法识别，请检查
     */
    @PostMapping("/picPathsUpload")
    @ResponseBody
    public AjaxResult picPathsUpload(String  paths) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath() + "/pic";

            Assert.notNull(paths,"没有上传封面");
            String[] pathArray = paths.split(",");
            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, file);
            //String url = serverConfig.getUrl() + fileName;
//            System.out.println("picToWord");
            logger.info("picToWord");
            ITesseract instance = new Tesseract();
            logger.info("datapath:"+testResourcesLanguagePath);
            instance.setDatapath(testResourcesLanguagePath);
            instance.setLanguage("chi_sim");
            StringBuffer sb = new StringBuffer();
            int _fileSize = pathArray.length;
            // 正确识别数量
            int rightSize = 0;
            for (String _p: pathArray) {
                String absolutPath = Global.getProfile() + _p.substring(Constants.RESOURCE_PREFIX.length());
                File imageFile = new File(absolutPath);
                String _result = "";
                try{
                    _result = instance.doOCR(imageFile);
                    rightSize++;
                }catch (Exception e){
                    logger.error(e.getMessage());
                    logger.error("[{}]，图片转文字失败",absolutPath,e);
                }
                sb.append(_result);
                sb.append("\r\n");
            }
            logger.info("图片转文字:[{}]",sb.toString());
            String msg = "";
            if(_fileSize==rightSize){
                msg = "识别正确";
            }
            if(_fileSize > rightSize && rightSize != 0){
                msg = "有图片无法识别，请检查";
            }
            if(rightSize == 0){
                msg = "识别失败，无法识别";
            }
            AjaxResult ajax = AjaxResult.success(msg);
            ajax.put("result", sb.toString());
            return ajax;
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询审读样本列表
     */
//    @RequiresPermissions("publish:sample:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RvSample rvSample) {
        startPage();
        List<RvSample> list = rvSampleService.selectRvSampleList(rvSample);
        return getDataTable(list);
    }

    /**
     * 导出审读样本列表
     */
//    @RequiresPermissions("publish:sample:export")
    @Log(title = "审读样本", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RvSample rvSample) {
        List<RvSample> list = null;
        if (StringUtils.isNotEmpty(rvSample.getExportIds())) {
            list = rvSampleService.selectRecordByIds(rvSample.getExportIds().split(","));
        } else {
            list = rvSampleService.selectRvSampleList(rvSample);
        }
        ExcelUtil<RvSample> util = new ExcelUtil<RvSample>(RvSample.class);
        return util.exportExcel(list, "sample");
    }

    /**
     * 新增审读样本
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存审读样本
     */
//    @RequiresPermissions("publish:sample:add")
    @Log(title = "审读样本", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(RvSample rvSample) {
        rvSample.setCreateName(ShiroUtils.getLoginName());
        rvSample.setCreateBy(ShiroUtils.getUserId().toString());
        rvSample.setCreateTime(new Date());
        rvSample.setReviewId(ReviewConstant.REVIEW_UNREAD);

        return toAjax(rvSampleService.insertRvSample(rvSample));
    }

    /**
     * 修改审读样本
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        RvSample rvSample = rvSampleService.selectRvSampleById(id);
        mmap.put("rvSample", rvSample);
        return prefix + "/edit";
    }

    /**
     * 查看审读样本
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        RvSample rvSample = rvSampleService.selectRvSampleById(id);
        mmap.put("rvSample", rvSample);
        return prefix + "/detail";
    }

    /**
     * 修改保存审读样本
     */
//    @RequiresPermissions("publish:sample:edit")
    @Log(title = "审读样本", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(RvSample rvSample) {
        rvSample.setUpdateName(ShiroUtils.getLoginName());
        rvSample.setUpdateBy(ShiroUtils.getUserId().toString());
        rvSample.setUpdateTime(new Date());
        return toAjax(rvSampleService.updateRvSample(rvSample));
    }

    /**
     * 删除审读样本
     */
//    @RequiresPermissions("publish:sample:remove")
    @Log(title = "审读样本", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(rvSampleService.deleteRvSampleByIds(ids));
    }


    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {

        ExcelUtil<RvSample> util = new ExcelUtil<RvSample>(RvSample.class);
        List<RvSample> list = new ArrayList<>();
        RvSample rvSample = new RvSample();
        //样本名称
        rvSample.setName("城口报(示范)");
        //样本介质
        rvSample.setMedium("ts");
        //出版单位
        rvSample.setPublisher("城口报社");
        //期刊主分类
        rvSample.setJournalSuper("区县报");
        //期刊子分类
        rvSample.setJournalSub("周二五(示范)");
        //缴送时间
        rvSample.setDeliveryTime(new Date());
        //出版标识
        rvSample.setIdentification("123(示范)");
        list.add(rvSample);

        return util.importDataTemplateExcel(list, "审读样本数据");
    }

    @Log(title = "审读样本excel导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String year) throws Exception {
        byte[] bytes = file.getBytes();
        InputStream in = new ByteArrayInputStream(bytes);

        ExcelUtil<RvSample> util = new ExcelUtil<RvSample>(RvSample.class);
        List<RvSample> userList = util.importExcel(in);

        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = rvSampleService.importRvSample(userList, updateSupport, operName, year, String.valueOf(ShiroUtils.getSysUser().getUserId()));
        return AjaxResult.success(message);
    }
}
